'use client';

import { useEffect, useState } from 'react';
import { Button, Menu, Pagination, List, Card, message, Tag, Spin } from 'antd';
import { useUser } from '../../context/userContext';
import api from '../../utils/api';
import styles from '@/components/Font.module.css';

// 封装错误处理函数
const handleError = (error, messageText) => {
  console.error(messageText, error);
  message.error("网络请求失败，请检查网络连接");
};

export default function PostManagementPage() {
  const { user } = useUser();
  const accessToken = user ? user.access_token : "";

  // 新增帖子展示相关状态
  const [postCategories, setPostCategories] = useState([]);
  const [postList, setPostList] = useState([]);
  const [postTotal, setPostTotal] = useState(0);
  const [postPage, setPostPage] = useState(1);
  const [postPageSize] = useState(6); // 增加每页显示数量
  const [currentPostCategory, setCurrentPostCategory] = useState("all");
  const [loading, setLoading] = useState(false);

  // 新增置顶相关状态
  const [isPinning, setIsPinning] = useState(false);
  const [isUnpinning, setIsUnpinning] = useState(false);

  // 新增置顶相关处理函数
  const handlePinPost = async (postId) => {
    setIsPinning(true);
    try {
      const response = await api.put(
        "/posts/pin",
        {},
        {
          params: { id: postId },
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );
      if (response.data.success) {
        message.success("帖子置顶成功！");
        // 重新获取帖子列表
        await fetchPostsList(currentPostCategory, postPage);
      }
    } catch (error) {
      handleError(error, "置顶帖子出错");
    } finally {
      setIsPinning(false);
    }
  };

  const handleUnpinPost = async (postId) => {
    setIsUnpinning(true);
    try {
      const response = await api.put(
        "/posts/unpin",
        {},
        {
          params: { id: postId },
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );
      if (response.status === 200) {
        message.success("取消置顶成功！");
        // 重新获取帖子列表
        await fetchPostsList(currentPostCategory, postPage);
      }
    } catch (error) {
      handleError(error, "取消置顶出错");
    } finally {
      setIsUnpinning(false);
    }
  };

  // 新增获取帖子分类
  const fetchPostCategories = async () => {
    try {
      const response = await api.get("/categories/all", {
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      if (response.data && Array.isArray(response.data.Reponse)) {
        setPostCategories(response.data.Reponse);
      }
    } catch (error) {
      handleError(error, "获取帖子分类失败");
    }
  };

  // 新增获取帖子列表
  const fetchPostsList = async (category = "all", page = 1) => {
    setLoading(true);
    try {
      let url = "/posts/list";
      let params = { page, pageSize: postPageSize };

      if (category !== "all") {
        url = "/posts/category";
        params = { ...params, categoryId: category };
      }

      const response = await api.get(url, {
        params,
        headers: { Authorization: `Bearer ${accessToken}` },
      });

      if (response.data && Array.isArray(response.data.posts)) {
        const postsWithAuthor = await Promise.all(
          response.data.posts.map(async (post) => {
            try {
              const userResponse = await api.get("/users/info", {
                params: { id: post.authorId },
              });
              const pinnedStatus = post.Pinned || false;
              return {
                ...post,
                authorDisplayName:
                  userResponse.data?.display_name || "未知作者",
                isPinned: pinnedStatus,
              };
            } catch (error) {
              return {
                ...post,
                authorDisplayName: "未知作者",
                isPinned: false,
              };
            }
          })
        );

        setPostList(postsWithAuthor);
        setPostTotal(response.data.total || 0);
      }
    } catch (error) {
      handleError(error, "获取帖子列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPostCategories();
    fetchPostsList(currentPostCategory, postPage);
  }, [currentPostCategory, postPage]);

  return (
    <div className="bg-[#F4EDEB] rounded-2xl shadow-md p-6 h-full flex flex-col">
      {/* 固定标题区域 */}
      <div className="mb-4">
        <h2 className={`${styles.titlesmall} text-xl mb-6 text-[#7A6E6E]`}>帖子管理</h2>
        
        <Menu
          mode="horizontal"
          selectedKeys={[currentPostCategory]}
          className="bg-white rounded-lg shadow-sm overflow-hidden"
          itemIconRender={() => null}
          selectable
          onSelect={({ key }) => {
            setCurrentPostCategory(key);
            setPostPage(1);
          }}
        >
          <Menu.Item key="all">全部</Menu.Item>
          {postCategories.map((category) => (
            <Menu.Item key={category.id}>{category.name}</Menu.Item>
          ))}
        </Menu>
      </div>

      {/* 可滚动的帖子内容区域 */}
      <div className="flex-1 overflow-y-auto mt-2 mb-4 pr-1">
        <Spin spinning={loading}>
          <List
            itemLayout="vertical"
            dataSource={postList}
            renderItem={(item) => (
              <Card 
                className="bg-white rounded-xl shadow-sm mb-3 overflow-hidden hover:shadow-md transition-shadow p-3" // 减小间距和内边距
                hoverable
              >
                <div className="flex justify-between items-start">
                  <Card.Meta
                    title={<span className={`${styles.text} font-medium text-base`}>{item.title}</span>} // 减小标题字体
                    description={`作者：${item.authorDisplayName}`}
                  />
                  {item.isPinned && (
                    <Tag 
                      color="#D6A7A1" 
                      className="ml-2"
                      style={{ fontFamily: 'var(--font-secondary)', fontSize: 10, height: 18, lineHeight: '18px' }} // 减小标签尺寸
                    >
                      置顶
                    </Tag>
                  )}
                </div>
                <div className={`${styles.text} mt-1 text-gray-700 text-sm line-clamp-2`}>{item.content}</div> {/* 减小字体并限制行数 */}

                {/* 操作按钮 */}
                <div className="mt-2 flex justify-end space-x-1"> {/* 减小间距 */}
                  {item.isPinned ? (
                    <Button
                      type="primary"
                      danger
                      className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-xs px-2 py-0.5" // 减小按钮尺寸
                      onClick={() => handleUnpinPost(item.id)}
                      disabled={isUnpinning || isPinning}
                      loading={isUnpinning}
                    >
                      取消置顶
                    </Button>
                  ) : (
                    <Button
                      type="primary"
                      className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-xs px-2 py-0.5" // 减小按钮尺寸
                      onClick={() => handlePinPost(item.id)}
                      disabled={isPinning || isUnpinning}
                      loading={isPinning}
                    >
                      置顶帖子
                    </Button>
                  )}
                </div>
              </Card>
            )}
          />
        </Spin>
      </div>

      {/* 固定分页区域 */}
      <div className="flex justify-center">
        <Pagination
          current={postPage}
          pageSize={postPageSize}
          total={postTotal}
          onChange={(newPage) => setPostPage(newPage)}
          className="bg-white p-2 rounded-lg shadow-sm text-sm" // 减小分页字体
        />
      </div>
    </div>
  );
}